<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('user_coupons', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade')->comment('用户ID');
            $table->foreignId('coupon_id')->constrained()->onDelete('cascade')->comment('优惠券模板ID');
            $table->string('code')->unique()->comment('优惠券码，自动生成唯一码');
            $table->enum('status', ['unused', 'used', 'expired'])
                ->default('unused')
                ->comment('状态：unused=未使用, used=已使用, expired=已过期');
            $table->timestamp('received_at')->comment('领取时间');
            $table->timestamp('used_at')->nullable()->comment('使用时间');
            $table->timestamp('expire_at')->comment('过期时间');
            $table->foreignId('order_id')->nullable()->constrained()->onDelete('set null')->comment('关联的订单ID');
            $table->decimal('discount_amount', 10, 2)->nullable()->comment('实际优惠金额');
            $table->timestamps();
            
            $table->index(['user_id', 'status']);
            $table->index('code');
            $table->index('expire_at');
            $table->index('coupon_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user_coupons');
    }
};
